const app = getApp()

Page({
  data: {
    statusBarHeight: 0,             // 系统栏高度
    data: [],                       // 数据组
    is_edit: false,                 // 是否为修改状态
    nowDate: null,                   // 当前日期
    region: ['上海市', '上海市', '黄浦区'],
    resultArray: [],
    defalut: "请选择  >",
    address: {},
    addressCode: '',
    detailAddress: [],
    dzKey: '',
    jwbsVal: []
  },
  onLoad: async function () {
    this.setData({
      statusBarHeight: await this.getDeviceBarHeight(),
    })
  },
  onShow: function () {
    this.getUserInfo()
    this.getCurrentDate()
  },
  bindAddressTextInput: function (e) {
    const key = e.currentTarget.dataset.key.id;
    this.setData({
      addressCode: key
    })
    const value = e.detail.value;
    const name = e.currentTarget.dataset.name;
    console.log('eee3', e)
    for (var i = 0; i < e.currentTarget.dataset.key.list.length; i++) {
      var obj = e.currentTarget.dataset.key.list[i];
      if (obj.placeHolder == name) {
        const deCode = obj.deCode;
        this.data.address[i] = value;

      }
    }
    console.log('address', this.data.address)
  },
  bindRegionChange: function (e) {
    const key = e.currentTarget.dataset.key.id;
    const j = 'resultArray[' + e.currentTarget.dataset.index + ']';
    console.log('key', key)
    console.log('j', j)

    this.setData({
      [j]: e.detail.value,
      addressCode: key
    })

    // for (var i = 0; i < e.currentTarget.dataset.key.list.length; i++) {
    //   var obj = e.currentTarget.dataset.key.list[i];
    //   console.log('obj',obj)
    // }
    let arr = this.data.address
    e.detail.value.forEach((item, index) => {

      arr[index] = item
    })
    console.log('arr', arr)
    this.setData({
      address: arr
    })
    console.log('address', this.data.address)
    // this.data.address = arr;

  },
  /**
   * 选择下拉属性
   */
  handleChangeSelect: function (e) {
    const id = e.currentTarget.dataset.id
    const list = e.currentTarget.dataset.list
    const index = Number(e.detail.value)
    const value = list[index]
    this.setValue(id, value)
  },
  /**
   * 改变日期
   * * 如果是 出生日期和预产期 都改变 孕周
   */
  handleChangeDate: function (e) {
    const id = e.currentTarget.dataset.id
    const value = e.detail.value
    let unset = false
    // 如果是出生日期
    if (id == 'Pub1100004') {
      let _date = this.getValue()['Pub1100006']
      _date = (_date - 280) * 24 * 3600 * 1000
      let date = new Date(value).getTime() + _date
      let target = new Date(date),
        year = target.getFullYear(),
        month = target.getMonth() + 1,
        day = target.getDate()
      let val = `${year}-${this.addZore(month)}-${this.addZore(day)}`
      this.setValue('Pub1100005', val)
    }
    // 如果是预产期
    if (id == 'Pub1100005') {
      let _date = this.getValue()['Pub1100006']
      _date = (_date - 280) * 24 * 3600 * 1000
      let date = new Date(value).getTime() + _date
      let target = new Date(date),
        year = target.getFullYear(),
        month = target.getMonth() + 1,
        day = target.getDate()
      let val = `${year}-${this.addZore(month)}-${this.addZore(day)}`
      this.setValue('Pub1100004', val)
    }

    // let days
    // if (id == 'Pub1100005') days = this.getDays2(value)
    // // 循环改变
    // this.data.data.forEach(item => {
    //     if (item.id === 'Pub1100006') {
    //         let arr = this.getWeek(days, 'array')
    //         item.transformValue = this.getWeek(days, 'string')
    //         item.value = days
    //         item.val = [item.multiArray[0].indexOf(arr[0]), item.multiArray[1].indexOf(arr[1])]
    //     }
    // })
    !unset && this.setValue(id, value)
  },
  addZore: function (num) {
    return num < 10 ? '0' + num : num
  },
  /**
   * 获取孕周天数
   * @param { string } value 出生日期
   */
  getDays: function (value) {
    let targetDate = new Date(this.getValue()['Pub1100005']).getTime() / 1000
    let birthDate = new Date(value).getTime() / 1000
    let reduce = Math.ceil((birthDate - targetDate) / 24 / 3600)
    return 280 + reduce
  },
  /**
   * 获取孕周天数
   * @param { string } value 出生日期
   */
  getDays2: function (value) {
    let birthDate = new Date(this.getValue()['Pub1100004']).getTime() / 1000
    let targetDate = new Date(value).getTime() / 1000
    let reduce = Math.ceil((birthDate - targetDate) / 24 / 3600)
    return 280 + reduce
  },
  /**
   * 改变时间
   * @param {*} e 
   */
  handleChangeTime: function (e) {
    const id = e.currentTarget.dataset.id
    const value = e.detail.value
    this.setValue(id, value)
  },
  /**
   * 输入
   */
  handleInput: function (e) {
    const id = e.currentTarget.dataset.id
    const value = e.detail.value
    this.setData({
      dzKey: id
    })
    this.setValue(id, value)
  },
  /**
   * 改变多选的状态只给预产期用
   * @param {*} e
   * * 改变孕周要跟预产期进行联动
   */
  handleChangeMulti: function (e) {
    const id = e.currentTarget.dataset.id
    const list = e.currentTarget.dataset.list
    let value = e.detail.value
    let day = list[0][value[0]] * 7
    day += list[1][value[1]]
    this.data.data.forEach(item => {
      if (id == item.id) {
        item.transformValue = this.getWeek(day, 'string')
        item.val = [value[0], value[1]]
        item.value = item.multiArray[0][value[0]] * 7 + item.multiArray[1][value[1]]
        this.data.data.forEach(d => {
          if (d.id == 'Pub1100005') {
            const date = this.getDate(item.value)
            d.value = date
          }
        })
      }
    })
    this.setData({ data: this.data.data })
    this.setValue(id, day)
  },
  /**
   * 获取日期
   * @param { number } value 孕周天数
   */
  getDate: function (value) {
    let targetValue = (280 - value) * 3600 * 24
    let birthDate = new Date(this.getValue()['Pub1100004']) / 1000
    let targetDate = new Date((birthDate + targetValue) * 1000),
      year = targetDate.getFullYear(),
      month = targetDate.getMonth() + 1,
      day = targetDate.getDate()
    function addZore(num) { return num < 10 ? '0' + num : num }
    return `${year}-${addZore(month)}-${addZore(day)}`
  },
  handleTapBoxAndInput(e) {
    console.log('病史', e)
    let jwbs = this.data.data.filter(item => {
      return item.id == 'jd_jwbs'
    })
    jwbs[0].value = JSON.stringify(e.detail.value)

  },
  /**
   * 点击修改信息
   */
  handleEdit: function () {
    this.setData({ is_edit: true })
    // let newData =JSON.parse(this.data.data.filter(item=>{
    //     return item.id=='jd_jzdz'
    // })[0].value) 

    
    this.setData({
      address: this.data.data[this.data.dzKey],
      defalut: this.data.data[this.data.dzKey],
      // detailAddress:newData
    })
    
  },
  /**
   * 保存建档信息
   */
  handleSave: function () {
    /**
    * 2021 11 15
    * 如果没有住院号 床号时自动添加无
    * 只在 queueId 为 12fddxekyyzzqueue001 生效
    */
    if (app.globalData.queueId === '12fddxekyyzzqueue001') {
      if (this.data.data[16].id == "Pub12x00008") {
        if ((!this.data.data[16].value.match(/[0-9]{6}-[0-9]{2}/) ||
          this.data.data[16].value.length !== 9)) {
          return this.showModal('住院号需写成 123456-01 的格式', 'hospitalNoFlag');
        }
      }

      if (this.data.data[17].id == "zcejd_ch") {
        if (this.data.data[17].value === '+') {
          return this.showModal('床号：固定3位字符(示例：001，+01)', 'bedNoFlag');
        }
        if (!this.data.data[17].value.match(/(^(\+)[0-9]{0,2}$)|(^[0-9]{0,3}$)/)) {
          return this.showModal('床号：固定3位字符(示例：001，+01)', 'bedNoFlag');
        }
      }
    }
    wx.showLoading({
      title: '提交中...'
    })
    // let arr = []
    // for (const key in  this.data.address) {
    //     if (Object.hasOwnProperty.call( this.data.address, key)) {
    //         const element =  this.data.address[key];
    //         arr.push(element)
    //     }
    // }
    // console.log('arr',arr)
    // let address=[...this.data.address]

    // this.data.data[this.data.addressCode] =JSON.stringify([...address,...arr]) 
    console.log('save', this.data.address)
    console.log('this.data.addressCode', this.data.addressCode)
    this.setValue(this.data.addressCode, JSON.stringify(this.data.address))
    // this.data.data.forEach(item=>{
    //   if(item.id=="Pub1100003"){
    //     item.value = item.value + "孩"
    //   }
    // })
    console.log('form111111111111111111', this.data.data)
    // return 
    this.saveInfo(this.data.data)
      .then(res => {
        wx.hideLoading()
        if (res.code == 0) {
          wx.showToast({
            icon: 'success',
            title: '保存成功!'
          })
          this.getUserInfo()
          this.setData({
            is_edit: false
          })
          return
        }
        wx.showToast({
          icon: 'none',
          title: '提交失败请重新尝试!'
        })
      })
      .catch(err => {
        if (err == 'error') {
          wx.showToast({
            icon: 'none',
            title: '提交失败请重新尝试!'
          })
          wx.hideLoading()
        }
      })
  },
  showModal: function (text, type) {
    wx.showModal({
      title: '提示',
      content: text,
      confirmText: '重新输入',
      cancelText: '跳过',
      showCancel: false,
      success: (res) => {

      },
    })
  },
  /**
   * 获取值
   */
  getValue: function () {
    let result = {}
    this.data.data.forEach(item => {
      result[item.id] = item.value
    })
    return result
  },
  /**
   * 写入数据
   * @param { string | string[] } id
   * @param { string | string[] } value
   */
  setValue: function (id, value) {
    if (Object.prototype.toString.call(id) === '[object Array]') {
      id.forEach((name, index) => {
        this.data.data.forEach(item => {
          if (item.id == name) item.value = value[index]
        })
      })
    } else {
      this.data.data.forEach(item => {
        if (id == item.id) item.value = value
      })
    }
    this.setData({ data: this.data.data })
  },
  /**
   * 获取用户详细信息
   */
  getUserInfo: async function () {
    const datas = await this.getCurrentUserInfo()
    console.log("datas", datas);
    const params = await this.getUserInfoData()
    var data = []
    if (datas.templId == 'scan_xinxueguantmp001' || datas.templId == 'scan_gaoxueyatmp001') {
      data = params.slice(0, 4)
    } else {
      data = params
    }
    console.log('data', data);
    // let val = data.filter(item=>{
    //     return item.type == 'checkboxAndInput'
    // })[0].value
    let val = ""
    let arr = data.filter(item => {
      return item.type == 'checkboxAndInput'
    })
    if (arr.length) {
      val = arr[0].value
      this.setData({
        jwbsVal: JSON.parse(val)
      })
    }
    console.log('val', val)
    console.log('jwbs', this.data.jwbsVal)
    data.forEach(item => {
      if (item.id == 'Pub1100006') {
        item.transformValue = this.getWeek(item.value, 'string')
      }
      if (item.type == 'select') {
        item.options = []
        item.list.forEach((l, i) => {
          item.options.push(l.text)
          if (l.text == item.value) item.index = String(i)
        })
      }
      if (item.type == 'gestation') {
        let week = [], day = [0, 1, 2, 3, 4, 5, 6]
        for (let i = item.minWeek; i < item.maxWeek + 1; i++) {
          week.push(i)
        }
        item.multiArray = [week, day]
        item.val = this.getWeek(item.value, 'array')
        item.val[0] = item.val[0] - 20
      }
      if (item.type == 'question_detailedaddress') {
        item.transformValue = item.value && JSON.parse(item.value).join(',')
      }
    })
    this.setData({ data })
  },
  /**
   * 获取当前日期
   */
  getCurrentDate: function () {
    let date = new Date(),
      year = date.getFullYear(),
      month = date.getMonth() + 1,
      day = date.getDate()
    function addZore(num) { return num < 10 ? '0' + num : num }
    let nowDate = `${year}-${addZore(month)}-${addZore(day)}`
    this.setData({ nowDate })
  },
  /**
   * 获取周
   * @param { number } day 怀孕天数
   * @param { string } type
   */
  getWeek: function (day, type) {
    const week = Math.floor(day / 7)
    const date = day % 7
    if (type == 'string') {
      return `${week == 0 ? '' : week + '周'}${date == 0 ? '' : date + '天'}`
    } else if (type == 'array') {
      return [week, date]
    }
  },
  /**
   * 获取工具栏高度
   */
  getDeviceBarHeight: function () {
    return new Promise(resolve => {
      wx.getSystemInfo({
        success: result => resolve(result.statusBarHeight)
      })
    })
  },
  /**
   * 返回上一页
   */
  handleBack: function () {
    wx.navigateBack()
  },
  /**
   * 获取用户信息数据
   */
  getUserInfoData: function () {
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.getUrl('/xcx/pt/queryArchiveInfo'),
        method: 'GET',
        header: wx.getStorageSync('cookie'),
        success: res => resolve(res.data.data.dataContent),
        fail: err => reject(err),
        complete: () => reject('error')
      })
    })
  },



  /**
   * 获取用户队列信息
   */
  getCurrentUserInfo: function () {
    return new Promise((resolve, reject) => {
      let {openid,accountId} = wx.getStorageSync('logindata')
      wx.request({
        // url: app.getUrl('/xcx/pt/getCurrentUserInfo'),
        url: app.getUrl(`/xcx/pt/getCurrentUserInfo?openId=${openid}&accountId=${accountId}`),
        method: 'GET',
        header: wx.getStorageSync('cookie'),
        success: res => resolve(res.data.data),
        fail: err => reject(err),
        complete: () => reject('error')
      })
    })
  },


  /**
   * 保存建档信息
   */
  saveInfo: function (data) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.getUrl('/xcx/pt/updateArchiveInfo'),
        method: "POST",
        header: wx.getStorageSync('cookie'),
        data: data,
        success: res => resolve(res.data),
        fail: err => reject(err),
        complete: () => reject('error')
      })
    })
  }
})